package com.guaniu.voip.sip;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;
 
public class UserHandlerThread extends Thread{
	private final String TAG = "UserHandlerThread";
    private boolean mReady;                             //  
    private boolean mRunning;                           //
    private final Object mReadyFence = new Object();    // Synchronize thread 
    private Handler mHandler;
    public void initHandler(){
		synchronized (mReadyFence) {
            if (mRunning) {
                Log.w(TAG, "Muxing thread running when start requested");
                return;
            }
            mRunning = true;
    		start();//runing.
            while (!mReady) {
                try {
                    mReadyFence.wait();
                } catch (InterruptedException e) {
                    // ignore
                }
            }
        }
	}
	
    public Handler getHandler(){
    	return mHandler;
    }
    
	public void exit(){
		if (mHandler != null){
            Log.w(TAG, "UserHandlerThread exit.");
			mHandler.getLooper().quit();
		}
	}
	
	@Override
	public void run() {
        Log.d(TAG, "Starting looper");

        Looper.prepare();
        synchronized (mReadyFence) {
            Log.d(TAG, "setting mHandler");
            mHandler = new Handler();
            Log.d(TAG, "setting mHandler to: " + mHandler);
            mReady = true;
            mReadyFence.notify();
        } 
        Looper.loop();

        synchronized (mReadyFence) {
            mReady = false;
            mHandler = null;
        }
        mRunning = false;
        Log.d(TAG, "shutting down looper"); 
	}
	
}
